/*
 * ECARX Technology Limited is the owner of the copyright and the trade secret of this software.
 * Without permission, no one has the right to obtain, disclose or use this software in any way.
 */

package com.ecarx.custom.view.time;

import android.content.ContentResolver;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.UserHandle;
import android.provider.Settings;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.jetbrains.annotations.Nullable;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class CustomTimeView extends FrameLayout {

    private static final String TAG = "CustomTimeViewTag";

    private UpdateFormatDateListener updateFormatDateListener;

    public final String TIME_24 = "24";
    public static final String LANGUAGE_CN = "zh";
    public final String CN_WEEK_MONTH = "M月d日 EEEE";
    public final String NOT_CN_WEEK_MONTH = "EEEE, d MMMM";

    private TextView tvLeft;
    private TextView tvTime;
    private TextView tvRight;

    private final int WHAT_UPDATE_TIME = 1001;

    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == WHAT_UPDATE_TIME) {
                setLocaleDateFormat();
                handler.sendEmptyMessageDelayed(WHAT_UPDATE_TIME, 1000);
            }
        }
    };

    public CustomTimeView(Context context) {
        this(context, null);
    }

    public CustomTimeView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomTimeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        View root = LayoutInflater.from(getContext()).inflate(R.layout.layout_time_view, this);
        root.setLayoutDirection(LAYOUT_DIRECTION_LTR);
        tvLeft = root.findViewById(R.id.tv_left);
        tvTime = root.findViewById(R.id.tv_time);
        tvRight = root.findViewById(R.id.tv_right);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        handler.sendEmptyMessage(WHAT_UPDATE_TIME);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        setLocaleDateFormat();
    }

    public void setAllTextColorRes(int colorRes) {
        try {
            setLeftColorRes(colorRes);
            setCenterColorRes(colorRes);
            setRightColorRes(colorRes);
        } catch (Exception e) {
            Log.d(TAG, "updateTimeTextColor error:" + e.getMessage());
        }
    }

    @SuppressWarnings("unused")
    public void setAllTextColor(int color) {
        try {
            setLeftColor(color);
            setCenterColor(color);
            setRightColor(color);
        } catch (Exception e) {
            Log.d(TAG, "updateTimeTextColor error:" + e.getMessage());
        }
    }

    public void setLeftColorRes(int leftColorRes) {
        try {
            if (tvLeft != null) {
                tvLeft.setTextColor(getResources().getColor(leftColorRes));
            }
        } catch (Exception e) {
            Log.d(TAG, "setLeftColor error:" + e.getMessage());
        }
    }

    public void setCenterColorRes(int centerColorRes) {
        try {
            if (tvTime != null) {
                tvTime.setTextColor(getResources().getColor(centerColorRes));
            }
        } catch (Exception e) {
            Log.d(TAG, "setCenterColor error:" + e.getMessage());
        }
    }

    public void setRightColorRes(int rightColorRes) {
        try {
            if (tvRight != null) {
                tvRight.setTextColor(getResources().getColor(rightColorRes));
            }
        } catch (Exception e) {
            Log.d(TAG, "setRightColor error:" + e.getMessage());
        }
    }

    public void setLeftColor(int leftColor) {
        if (tvLeft != null) {
            tvLeft.setTextColor(leftColor);
        }
    }

    public void setCenterColor(int centerColor) {
        if (tvTime != null) {
            tvTime.setTextColor(centerColor);
        }
    }

    public void setRightColor(int rightColor) {
        if (tvRight != null) {
            tvRight.setTextColor(rightColor);
        }
    }


    public void setAllTextSize(int size) {
        try {
            if (tvLeft != null) {
                tvLeft.setTextSize(getResources().getDimensionPixelSize(size));
            }
            if (tvTime != null) {
                tvTime.setTextSize(getResources().getDimensionPixelSize(size));
            }
            if (tvRight != null) {
                tvRight.setTextSize(getResources().getDimensionPixelSize(size));
            }
        } catch (Exception e) {
            Log.d(TAG, "updateTextSize error:" + e.getMessage());
        }
    }

    public void setLeftSize(int leftSize) {
        try {
            if (tvLeft != null) {
                tvLeft.setTextSize(getResources().getDimensionPixelSize(leftSize));
            }
        } catch (Exception e) {
            Log.d(TAG, "setLeftSize error:" + e.getMessage());
        }
    }

    public void setTimeSize(int timeSize) {
        try {
            if (tvTime != null) {
                tvTime.setTextSize(getResources().getDimensionPixelSize(timeSize));
            }
        } catch (Exception e) {
            Log.d(TAG, "setTimeSize error:" + e.getMessage());
        }
    }

    public void setRightSize(int rightSize) {
        try {
            if (tvRight != null) {
                tvRight.setTextSize(getResources().getDimensionPixelSize(rightSize));
            }
        } catch (Exception e) {
            Log.d(TAG, "setRightSize error:" + e.getMessage());
        }
    }

    public void setLabelMargin(int margin) {
        if (tvLeft != null) {
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) tvLeft.getLayoutParams();
            layoutParams.rightMargin = margin;
            tvLeft.setLayoutParams(layoutParams);
        }
        if (tvRight != null) {
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) tvRight.getLayoutParams();
            layoutParams.leftMargin = margin;
            tvRight.setLayoutParams(layoutParams);
        }
    }
    public String getFormatTime() {
        try {
            Method method = Settings.System.class.getDeclaredMethod("getStringForUser", ContentResolver.class, String.class,  int.class);
            method.setAccessible(true);
            Object invoke = method.invoke(Settings.System.class, getContext().getContentResolver(), Settings.System.TIME_12_24, -2);
            if (invoke instanceof String) {
                Log.i(TAG, "getFormatTime getStringForUser = " + (String) invoke);
                return (String) invoke;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.i(TAG, "getFormatTime Settings.System.getString = " + Settings.System.getString(getContext().getContentResolver(), Settings.System.TIME_12_24));
        return Settings.System.getString(getContext().getContentResolver(), Settings.System.TIME_12_24);
    }

    public void setLocaleDateFormat() {
        String mTimeFormat = getFormatTime();
        String language = Locale.getDefault().getLanguage();
        Log.d(TAG, "setLocaleDateFormat - mTimeFormat:" + mTimeFormat + "--language:" + language);
        Calendar calendar = Calendar.getInstance();
        if (TIME_24.equals(mTimeFormat)) {
            //24时制
            hideLeftRight();
            String strTime24 = forStrTime(calendar, "HH:mm");
            showStrTime(strTime24);

            Log.d(TAG, "NOW TIME IS " + strTime24);
        } else {
            //12时制
            String timeAmPm = getTimeAmPm(calendar);
            if (isCn(language)) {
                hideRight();
                showLeft(timeAmPm);
            } else {
                hideLeft();
                showRight(timeAmPm);
            }
            String strTime12 = forStrTime(calendar, "h:mm");
            showStrTime(strTime12);
            Log.d(TAG, "NOW TIME IS " + timeAmPm + "- " + strTime12);
        }
        if (updateFormatDateListener != null) {
            String nowTimeDate = forStrTime(calendar, isCn(language) ? CN_WEEK_MONTH : NOT_CN_WEEK_MONTH);
            Log.d(TAG, "nowTimeDate:" + nowTimeDate);
            //向外透出月、日、星期 字符串日期
            updateFormatDateListener.formatDate(
                    language,
                    calendar.get(Calendar.MARCH),
                    calendar.get(Calendar.DAY_OF_MONTH),
                    calendar.get(Calendar.DAY_OF_WEEK)
            );
        }
    }

    private String forStrTime(Calendar calendar, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.getDefault());
        Date time = calendar.getTime();
        return sdf.format(time);
    }

    private String getTimeAmPm(Calendar calendar) {
        int isAm = calendar.get(Calendar.AM_PM);
        String str12Label;
        if (isAm == Calendar.AM) {
            str12Label = getResources().getString(R.string.str_time_am);
        } else {
            str12Label = getResources().getString(R.string.str_time_pm);
        }
        return str12Label;
    }

    private void showStrTime(String strTime) {
        if (tvTime != null) {
            tvTime.setText(strTime);
        }
    }

    private void showLeft(String timeAmPm) {
        if (tvLeft != null) {
            tvLeft.setText(timeAmPm);
            tvLeft.setVisibility(VISIBLE);
        }
    }

    private void showRight(String timeAmPm) {
        if (tvRight != null) {
            tvRight.setText(timeAmPm);
            tvRight.setVisibility(VISIBLE);
        }
    }

    private void hideLeftRight() {
        hideLeft();
        hideRight();
    }

    private void hideLeft() {
        if (tvLeft != null) {
            tvLeft.setText("");
            tvLeft.setVisibility(GONE);
        }
    }

    private void hideRight() {
        if (tvRight != null) {
            tvRight.setText("");
            tvRight.setVisibility(GONE);
        }
    }

    public void setUpdateFormatDateListener(UpdateFormatDateListener updateFormatDateListener) {
        this.updateFormatDateListener = updateFormatDateListener;
    }

    private boolean isCn(String language) {
        return LANGUAGE_CN.equalsIgnoreCase(language);
    }
}
